package com.yingxin.yxerp.module.dingtalk.service.impl;

import com.itextpdf.text.pdf.BaseFont;
import com.yingxin.yx.framework.commons.constant.PathConst;
import com.yingxin.yx.framework.commons.exception.BizException;
import com.yingxin.yx.framework.commons.helper.PropertiesHelper;
import com.yingxin.yxerp.module.dingtalk.service.PdfService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.xhtmlrenderer.pdf.ITextRenderer;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.OutputStream;
import java.io.StringWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Calendar;
import java.util.Map;
import java.util.UUID;

@Slf4j
@Service
public class PdfServiceImplImpl implements PdfService {

    private static String filePath;

    /**
     * 获取新字符串模板
     */
    @Override
    public String getTemplate(String templateName, Map<String, Object> map) {
        String path = PropertiesHelper.getInstance().getProperty(PathConst.FTL_DIR);
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        // 判断有没有该模板
        String outputFile = file.getPath() + "/" + templateName;
        File fileTemplate = new File(outputFile);
        if (!fileTemplate.exists()) {
            throw new BizException("模板未找到,请检查模板文件");
        }

        Configuration configuration = new Configuration( Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS );
        String encoding = "UTF-8";

        ITextRenderer renderer = new ITextRenderer();
        try (ByteArrayOutputStream out = new ByteArrayOutputStream();)
        {
            // 设置 css中 的字体样式（暂时仅支持宋体和黑体） 必须，不然中文不显示
            renderer.getFontResolver().addFont(
            file.getPath() +"/" + "simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

            configuration.setDirectoryForTemplateLoading(file);
            Template template = configuration.getTemplate(templateName,encoding);
            StringWriter writer = new StringWriter();
            template.process(map, writer );
            writer.flush();

            String html = writer.toString();
            // 把html代码传入渲染器中
            renderer.setDocumentFromString( html );
            renderer.layout();

            renderer.createPDF( out, false );
            renderer.finishPDF();
            out.flush();

            String savePath = getPath( PropertiesHelper.getInstance().getProperty(PathConst.REPORT_DIR),"/Pdf");
            // 创建一个文件流
            String fileName = savePath +"\\"+ UUID.randomUUID().toString() + ".pdf";
            OutputStream outputStream = Files.newOutputStream( Paths.get( fileName ) );
            out.writeTo( outputStream );
            out.close();
            outputStream.close();

            // 格式化文件格式 - 并返回
            return fileName.replace( "D:\\yx-reportImage\\Pdf\\", "");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * html模版转pdf
     */
    @Override
    public String htmlToPdf(Map<String, Object> map, String templateName) {
        try {
            return getTemplate( templateName, map );
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 判断有无文件夹
     * @param reportDir
     * @param DirName
     * @return
     */
    private  String getPath(String reportDir,String DirName) {
        Calendar calendar = Calendar.getInstance();
        //年
        int year = calendar.get(Calendar.YEAR);
        //月
        int month = calendar.get(Calendar.MONTH) + 1;
        //日
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        String path = File.separator + File.separator + year
                + File.separator + month + File.separator + day + File.separator;
        File file = new File(reportDir+ DirName + path);
        if (!file.exists()) {
            file.mkdirs();
        }
        filePath = path;
        return file.getPath();
    }

}
